import asyncio, random, pymysql
from DBUtils import PooledDB


class Db:
    db_host = "localhost"
    db_username = "root"
    db_pwd = ""
    db_charset = "utf8"
    db_name = "test"
    pools = None
    cursor = None
    conn = None

    def __init__(self):
        self.pools = PooledDB(creator=pymysql, host=self.db_host, user=self.db_username, passwd=self.db_pwd,
                              db=self.db_name, port=3306, charset=self.db_charset, maxconnections=50, blocking=True)

    def query(self, sql):
        self.conn = self.pools.connection()
        self.cursor = self.conn.cursor()

    def close(self):
        self.cursor.close()
        self.conn.close()


# 子任务
async def test(x, rand):
    print("rand:" + str(rand))
    await asyncio.sleep(rand)
    return "updated" + str(x)


# 回调函数
def result(feature):
    print(feature.result())


# 主函数
async def main():
    i = 0
    tasks = []

    while i <= 10:
        rand = random.randint(0, 5)
        task = asyncio.ensure_future(test(i, rand))
        # task.add_done_callback(result)
        tasks.append(task)
        i += 1

    dones, pedding = await asyncio.wait(tasks)

    for task_status in dones:
        print(task_status.result())


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

loop.close()
